package com.zy.mydemo.api.service.impl;

import com.zy.mydemo.api.service.AuthService;
import com.zy.mydemo.common.entity.AuthEntity;
import com.zy.mydemo.common.entity.AuthParamEntity;
import com.zy.mydemo.common.entity.UserEntity;
import com.zy.mydemo.common.mapper.AuthMapper;
import com.zy.mydemo.common.utils.ResultUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author:zhongyong
 * @Description：
 * @Date：Create in 2020/05/08
 */
@Service
public class AuthServiceImpl implements AuthService {

    @Autowired(required = false)
    private AuthMapper authMapper;

    @Override
    public ResultUtils addAuth(AuthEntity auth) {
        if (auth == null) {
            return ResultUtils.error("参数异常");
        }

        if (StringUtils.isEmpty(auth.getAuthName())) {
            return ResultUtils.error("权限名称不能为空");
        }

        if (StringUtils.isEmpty(auth.getUrl())) {
            auth.setUrl("");
        }

        if (StringUtils.isEmpty(auth.getRemark())) {
            auth.setRemark("");
        }

        int id = authMapper.insertAuth(auth);
        if (id <= 0) {
            return ResultUtils.error("数据库异常,添加失败");
        }

        return ResultUtils.success("成功", id);
    }

    @Override
    public ResultUtils getList(AuthParamEntity param) {
        List<AuthEntity> list = authMapper.getList(param);
        return ResultUtils.success("成功", list);
    }

    @Override
    public ResultUtils getListByUser(UserEntity user) {
        if (user == null) {
            return ResultUtils.error("参数异常");
        }


        Boolean isSuperAdmin = user.getIsSuperAdmin() == 1 ? true : false;
        String roleIds = user.getRoleIds();
        List<Integer> roleIdList = null;
        if (!StringUtils.isEmpty(roleIds)) {
            roleIdList = Arrays.asList(roleIds.split(",")).stream()
                    .map(id -> Integer.parseInt(id)).collect(Collectors.toList());
        }

        AuthParamEntity param = new AuthParamEntity();
        if (!isSuperAdmin) {
            if (roleIdList == null || roleIdList.size() == 0) {
                return ResultUtils.error("没有任何权限");
            } else {
                param.setRoleIds(roleIdList);
            }
        }

        return getList(param);
    }
}
